package com.springsecurity.controller;

import com.springsecurity.utils.ValidCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class SecurityController {
	@GetMapping("/index")
	public String index() {
		return "index";
	}
	@GetMapping("/menu{num}/{id}")
	public String menu(@PathVariable int num,@PathVariable int id) {
		return "menu"+num+"/"+id;
	}
	@GetMapping("/toLogin")
	public String toLogin(HttpServletRequest request) {
		String msg=(String) request.getSession().getAttribute("msg");
		if (msg != null) {
			request.setAttribute("msg",msg);
		}
		return "login";
	}
	@GetMapping("/toLogin/error")
	public String toLoginError(HttpServletRequest request, Model model) {
		AuthenticationException authentication=(AuthenticationException)request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (authentication instanceof UsernameNotFoundException ||authentication instanceof BadCredentialsException) {
			model.addAttribute("msg","用户名或密码错误");
		} else if (authentication instanceof DisabledException){
			model.addAttribute("msg","用户被禁用");
		} else if (authentication instanceof LockedException) {
			model.addAttribute("msg","用户被锁定");
		} else if (authentication instanceof AccountExpiredException) {
			model.addAttribute("msg","用户账户过期");
		} else if (authentication instanceof CredentialsExpiredException) {
			model.addAttribute("msg","用户密码过期");
		}
		return "login";
	}
	@GetMapping("/validCode")
	public void getValidPicture(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ValidCode validCode=new ValidCode();
		BufferedImage image=validCode.getImage();
		String validcode = validCode.getValidCode();
		System.out.println("validCode：" + validcode);
		request.getSession().setAttribute("validCode",validcode);
		ValidCode.output(image,response.getOutputStream());
	}
	@GetMapping("/errorRole")
	public String errorRole(){
		return "/errorRole";
	}
}
